package cn.tedu.tvrd.controller;

import cn.tedu.tvrd.entity.Banner;
import cn.tedu.tvrd.mapper.BannerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class BannerController {
    @Autowired(required = false)
    BannerMapper mapper;

    @Value("${dirPath}")
    private String dirPath;

    @RequestMapping("/banner/select")
    public List<Banner> select(){
        return mapper.selectAll();
    }

    @RequestMapping("/banner/delete")
    public void delete(int id){
        //通过轮播图id 得到轮播图的文件名
        String fileName = mapper.selectFileName(id);
        //拼接出图片完整路径
        String filePath = dirPath+"/"+fileName;
        //删除文件
        new File(filePath).delete();

        mapper.delete(id);
    }

    @RequestMapping("/banner/add")
    public void add(MultipartFile file) throws IOException {
        //得到文件名
        String filename = file.getOriginalFilename();
        //得到后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        //得到唯一文件名
        filename = UUID.randomUUID()+suffix;

        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+"/"+filename;
        file.transferTo(new File(filePath));
        //创建一个Banner对象 把图片名赋值给url
        Banner banner = new Banner();
        banner.setUrl(filename);
        //调用mapper.insert(banner); 把数据保存到banner表
        mapper.insert(banner);

    }
}
